<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>OL</title>
    <link rel="stylesheet" href="lib/ol.css" type="text/css">
    <link rel="stylesheet" href="style/map.css" type="text/css">
    <style>
        .my-popup {
            white-space: nowrap;
            background-color: rgba(0,0,0, 0.8);
            border-radius: 0.5rem;
            --padding: 0.6rem;
            font-size: 0.8rem;
            position: relative;
            color: white;
        }

        .my-popup .title {
            font-weight: bold;
            width: 100%;
            padding: var(--padding);
            padding-bottom: 0;
        }

        .my-popup .close {
            float: right;
            cursor: pointer;
            font-size: 1.2rem;
            margin: -0.3rem 1.2rem;
        }

        .my-popup .content {
            padding: var(--padding);
        }

        .my-popup:after {
            content: ' ';
            position: absolute;
            width: 0;
            height: 0;
            border: 0.4rem solid transparent;
            border-top-color: rgba(0,0,0, 0.8);
            left: calc(50% - 0.4rem);
            top: 100%;
        }

    </style>
    <script src="lib/ol.js"></script>
</head>
<body>
<div id="map" class="map">
    <div class="my-popup" id="myPopup">
        <div class="title">
            点击位置
            <div id="popupClose" class="close">×</div>
        </div>
        <div class="content">
            <span id="popupContent"></span>
        </div>
    </div>
</div>
<script>
    const tile = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
        })
    })
    const zoom = 4, center = ol.proj.fromLonLat([107.11040599933166, 34.26271532332011])
    var map = new ol.Map({
        target: 'map',
        layers: [
            tile
        ],
        view: new ol.View({
            center,
            zoom
        })
    });
    let overlay= new ol.Overlay({
        element: document.getElementById('myPopup'),
        positioning: 'bottom-center',
        position: null,
        offset: [0, -5]
    })
    map.addOverlay(overlay)
    document.getElementById('popupClose').onclick = () => {
        overlay.setPosition(null)
    }
    map.on('click', function (e) {
        const lonlat = ol.proj.toLonLat(e.coordinate)
        document.getElementById('popupContent').innerText = lonlat.map(v => v.toFixed(4)).join(', ')
        overlay.setPosition(e.coordinate)
    })
</script>
</body>
</html>